package controller

import (
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	swaggerFiles "github.com/swaggo/files"
	ginSwagger "github.com/swaggo/gin-swagger"
	"goods-srv/internal/biz/dto"
	"goods-srv/internal/biz/middleware"
	"goods-srv/internal/biz/vo"
	"goods-srv/libs"
	"net/http"
)

type Router struct{}

// HandlerValidatorError 处理表单验证
func (_ Router) HandlerValidatorError(c *gin.Context, err error) {
	var errs validator.ValidationErrors
	ok := errors.As(err, &errs)
	if !ok {

		apiRes := vo.NewFail()
		if err.Error() == "EOF" {
			apiRes.Msg = "参数错误"
		} else {
			apiRes.Msg = err.Error()
		}
		c.JSON(http.StatusOK, apiRes)
		c.Abort() // 拦截，不能继续执行
		return    // 并阻止后面程序执行
	}
	apiRes := vo.NewFail()
	// 使用初始化的 formValidator.Trans
	apiRes.Msg = dto.RemoveTopStruct(errs.Translate(dto.Trans))
	c.JSON(http.StatusOK, apiRes)
}

func SetUp() *gin.Engine {
	gin.SetMode(gin.ReleaseMode) // 设置为发布模式，默认开发模式

	router := gin.New()

	// 设置静态资源目录
	//router.Static("/assets", "./assets")

	// http://127.0.0.1:8090/swagger/index.html
	router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

	// 注册中间件
	router.Use(
		middleware.Cors(),                         // 开启跨域
		middleware.GinLogger(libs.Logger),         // 接口日志记录
		middleware.GinRecovery(libs.Logger, true), // 移除捕获记录
	)

	NewIndex(router)
	return router
}
